// Copyright 2019 Prometheus Team
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package webhook

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"regexp"
	"strings"

	"github.com/go-kit/log"
	commoncfg "github.com/prometheus/common/config"

	"github.com/prometheus/alertmanager/config"
	"github.com/prometheus/alertmanager/notify"
	"github.com/prometheus/alertmanager/template"
	"github.com/prometheus/alertmanager/types"
)

// Notifier implements a Notifier for generic webhooks.
type Notifier struct {
	conf    *config.WebhookConfig
	tmpl    *template.Template
	logger  log.Logger
	client  *http.Client
	retrier *notify.Retrier
}

// New returns a new Webhook.
func New(conf *config.WebhookConfig, t *template.Template, l log.Logger, httpOpts ...commoncfg.HTTPClientOption) (*Notifier, error) {
	client, err := commoncfg.NewClientFromConfig(*conf.HTTPConfig, "webhook", httpOpts...)
	if err != nil {
		return nil, err
	}
	return &Notifier{
		conf:   conf,
		tmpl:   t,
		logger: l,
		client: client,
		// Webhooks are assumed to respond with 2xx response codes on a successful
		// request and 5xx response codes are assumed to be recoverable.
		retrier: &notify.Retrier{
			CustomDetailsFunc: func(_ int, body io.Reader) string {
				return errDetails(body, conf.URL.String())
			},
		},
	}, nil
}

// Message defines the JSON object send to webhook endpoints.
type Message struct {
	*template.Data

	// The protocol version.
	Version         string `json:"version"`
	GroupKey        string `json:"groupKey"`
	TruncatedAlerts uint64 `json:"truncatedAlerts"`
}

func truncateAlerts(maxAlerts uint64, alerts []*types.Alert) ([]*types.Alert, uint64) {
	if maxAlerts != 0 && uint64(len(alerts)) > maxAlerts {
		return alerts[:maxAlerts], uint64(len(alerts)) - maxAlerts
	}

	return alerts, 0
}

// Notify implements the Notifier interface.
func (n *Notifier) Notify(ctx context.Context, alerts ...*types.Alert) (bool, error) {
	//alerts, _ := truncateAlerts(n.conf.MaxAlerts, alerts)
	alerts, _ = truncateAlerts(n.conf.MaxAlerts, alerts)
	data := notify.GetTemplateData(ctx, n.tmpl, alerts, n.logger)

	//groupKey, err := notify.ExtractGroupKey(ctx)
	//if err != nil {
	//	level.Error(n.logger).Log("err", err)
	//}

	//msg := &Message{
	//	Version:         "4",
	//	Data:            data,
	//	GroupKey:        groupKey.String(),
	//	TruncatedAlerts: numTruncated,
	//}
	// tmp := convertDataToFeishu(data)
	tmp, linkmsgs := convertDataToFeishu(data)
	var msg map[string]interface{}
	if len(linkmsgs) > 0 {
		//msg结构
		linkMsg := DeduplicateLinkMsg(linkmsgs)
		msg = map[string]interface{}{
			"msg_type": "post",
			"content": map[string]map[string]interface{}{
				"post": {
					"zh_cn": map[string]interface{}{
						"content": []interface{}{},
					},
				},
			},
		}
		//文本内容
		content := []interface{}{
			map[string]interface{}{
				"tag":  "text",
				"text": tmp,
			},
		}
		//超链接内容
		for _, linkMsg := range linkMsg {
			content = append(content, map[string]interface{}{
				"tag":  "a",
				"text": linkMsg.Title,
				"href": linkMsg.Url,
			})
		}
		msg["content"].(map[string]map[string]interface{})["post"]["zh_cn"].(map[string]interface{})["content"] = []interface{}{content}
	} else {
		msg = map[string]interface{}{
			"msg_type": "text",
			"content": map[string]string{
				"text": tmp,
			},
		}
	}
	fmt.Println("msg:", msg)
	var buf bytes.Buffer
	if err := json.NewEncoder(&buf).Encode(msg); err != nil {
		return false, err
	}
	var url string
	if n.conf.URL != nil {
		url = n.conf.URL.String()
	} else {
		content, err := os.ReadFile(n.conf.URLFile)
		if err != nil {
			return false, fmt.Errorf("read url_file: %w", err)
		}
		url = strings.TrimSpace(string(content))
	}

	resp, err := notify.PostJSON(ctx, n.client, url, &buf)
	if err != nil {
		return true, notify.RedactURL(err)
	}
	defer notify.Drain(resp)

	shouldRetry, err := n.retrier.Check(resp.StatusCode, resp.Body)
	if err != nil {
		return shouldRetry, notify.NewErrorWithReason(notify.GetFailureReasonFromStatusCode(resp.StatusCode), err)
	}
	return shouldRetry, err
}

func errDetails(body io.Reader, url string) string {
	if body == nil {
		return url
	}
	bs, err := io.ReadAll(body)
	if err != nil {
		return url
	}
	return fmt.Sprintf("%s: %s", url, string(bs))
}
func convertDataToFeishu(data *template.Data) (string, []LinkMsg) {
	var text string
	var linkMsgs []LinkMsg
	if data.Status == "firing" {
		text += "🔥"
	} else {
		text += "✅"
	}
	text += "\n"
	for _, alert := range data.Alerts {
		elems := alert.Annotations.Values()
		temp := strings.Join(elems, ",")
		linkPattern := regexp.MustCompile(`#\(tag\)\(a\)\s*text:([^,]+),\s*href:([^，\s]+)`)
		if linkPattern.MatchString(temp) {
			result, linkMsg := splitMsgForTag(temp)
			text += result + "\n"
			linkMsgs = append(linkMsgs, linkMsg...)
		} else {
			text += temp + "\n"
		}
	}
	return text, linkMsgs
}

type LinkMsg struct {
	Title string `json:"title"`
	Url   string `json:"url"`
}

func splitMsgForTag(data string) (string, []LinkMsg) {
	var result string
	var linkMsgs []LinkMsg
	textPattern := regexp.MustCompile(`#\(tag\)\(text\)(.*?)#\(tag\)\(a\)`)
	linkPattern := regexp.MustCompile(`#\(tag\)\(a\)\s*text:([^,]+),\s*href:([^，\s]+)`)

	// 处理#(tag)(a)类型内容
	linkMatchs := linkPattern.FindAllStringSubmatch(data, -1)
	for _, linkMatch := range linkMatchs {
		linkMsg := LinkMsg{
			Title: linkMatch[1],
			Url:   linkMatch[2],
		}
		linkMsgs = append(linkMsgs, linkMsg)
	}

	// 处理#(tag)(text)类型内容
	textMatch := textPattern.FindStringSubmatch(data)
	if len(textMatch) > 1 {
		result = textMatch[1]
	} else {
		result = data
	}
	return result, linkMsgs
}

// 去重LinkMsg切片
func DeduplicateLinkMsg(linkMsg []LinkMsg) []LinkMsg {
	var result []LinkMsg
	seen := make(map[string]bool)
	for _, msg := range linkMsg {
		key := msg.Url + msg.Title
		if !seen[key] {
			seen[key] = true
			result = append(result, msg)
		}
	}
	return result
}
